package com.heima.article.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.es.ApArticleSearch;
import com.heima.article.es.ApArticleSearchRepository;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 请不要叫我高司令
 * @Date 2022/4/15 22:35
 * @Version 1.0
 */

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private Configuration configuration;


    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    private MinIOService minIOService;

    @GetMapping("/html/{id}")
    public ResponseResult createHtml(@PathVariable Long id) throws IOException, TemplateException {
        //根据id查询文章
        LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleContent::getArticleId, id);
        ApArticleContent articleContent = contentService.getOne(queryWrapper);

        //获取模板
        Template template = configuration.getTemplate("article.ftl");
        //写入数据
        Map<String, Object> map = new HashMap<>();
        map.put("content", JSON.parseArray(articleContent.getContent()));

        //合并模板和数据
        StringWriter out = new StringWriter();
        template.process(map, out);

        //生成静态页面上传到minIO
        String objectName = id + ".html";
        InputStream is = new ByteArrayInputStream(out.toString().getBytes());
        String url = minIOService.upload(objectName, is, "text/html");
        return ResponseResult.okResult(url);
    }

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 创建es索引
     * @return
     */
    @GetMapping("/createIndex")
    public ResponseResult createIndex() {
        boolean index = elasticsearchRestTemplate.createIndex(ApArticleSearch.class);
        return ResponseResult.okResult(index);
    }

    @GetMapping("/deleteIndex")
    public ResponseResult deleteIndex() {

        boolean index = elasticsearchRestTemplate.deleteIndex(ApArticleSearch.class);
        return ResponseResult.okResult(index);

    }
    /**
     * 添加映射
     *
     * @return
     */
    @GetMapping("/putMapping")
    public ResponseResult putMapping() {
        boolean mapping = elasticsearchRestTemplate.putMapping(ApArticleSearch.class);
        return ResponseResult.okResult(mapping);
    }

    @Autowired
    private IApArticleService apArticleService;

    /**
     * 保存文章列表
     *
     * @return
     */
    @GetMapping("/addDoc")
    public ResponseResult addDoc() {

        // 将数据库已有的文章信息同步到es中
        // 从MySQL中查询文章列表
        List<ApArticle> articles = apArticleService.list();
        for (ApArticle article : articles) {
            ApArticleSearch search = new ApArticleSearch();
            BeanUtils.copyProperties(article, search);
            // 保存到es中
            IndexQuery indexQuery = new IndexQuery();
            indexQuery.setId(search.getId().toString());
            indexQuery.setObject(search);
            elasticsearchRestTemplate.index(indexQuery);
        }

        return ResponseResult.okResult();

    }

    @Autowired
    private ApArticleSearchRepository repository;

    @GetMapping("/del")
    public ResponseResult deleteAll(){

        repository.deleteAll();
        return ResponseResult.okResult();

    }

    @GetMapping("/add")
    public ResponseResult addAll(){

        // 从MySQL中查询文章列表
        List<ApArticle> articles = apArticleService.list();
        List<ApArticleSearch> list = new ArrayList<>();
        for (ApArticle article : articles) {
            ApArticleSearch search = new ApArticleSearch();
            BeanUtils.copyProperties(article, search);
            list.add(search);
        }
        repository.saveAll(list);
        return ResponseResult.okResult();

    }




}
